package com.shuziren.interceptor;


import com.shuziren.service.RedisService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        String userId1 = request.getHeader("username");

        if (token == null && userId1 == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        System.out.println("token:"+token);
        System.out.println("username:"+userId1);
        Object value = redisTemplate.get("OnlineUser:"+userId1);
        System.out.println("tokenredis"+value);

//         去掉 "Bearer " 前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        boolean equals = value.equals(token);
        System.out.println("equals:"+equals);
        if (!equals){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;

    }
}